<!-- eslint-disable prettier/prettier -->
<!-- eslint-disable vue/valid-v-for -->
<!-- eslint-disable vue/valid-attribute-name -->
<template>
  <el-form label-width="100px" class="demo-form-inline">
    <el-form-item label="spu名称">
      <el-input
        placeholder="输入SPU名称"
        label-width="200px"
        v-model="spuObject.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select
        v-model="spuObject.tmId"
        :placeholder="productName ? productName : '选择品牌'"
        @click="spuProduct"
      >
        <el-option
          v-for="item of productArr"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input
        type="textarea"
        placeholder="请你输入描述"
        v-model="spuObject.description"
      />
    </el-form-item>
    <el-form-item label="品牌LOGO" prop="logoUrl">
      <!-- upload组件属性:action图片上传路径书写/api,代理服务器不发送这次post请求  -->
      <el-upload
        v-model:file-list="spuImages"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="beforeAvatarUpload"
      >
        <!-- <img v-if="spuImgData.imgUrl" :src="spuImgData.imgUrl" class="avatar" /> -->
        <el-icon class="avatar-uploader-icon">
          <Plus />
        </el-icon>
        <el-dialog v-model="dialogVisible">
          <img
            w-full
            :src="imgUrl"
            alt="Preview Image"
            style="width: 100%; height: 100%"
          />
        </el-dialog>
      </el-upload>
    </el-form-item>
    <el-form-item label="SPU销售属性">
      <el-select v-model="saleAttrValueObject" :placeholder="unSelectSaleAttr.length > 0 ? `还未选择${unSelectSaleAttr.length}个` : `无属性可选择`">
        <el-option v-for="attr of unSelectSaleAttr" :key="attr.id" :label="attr.name" :value="`${attr.id}:${attr.name}`"></el-option>
      </el-select>
      <el-button style="margin: 10px" type="primary" size="default" icon="Plus" :disabled="saleAttrValueObject ? false : true" @click="pushAttr">
        添加属性值
      </el-button>
      <el-table border style="margin: 10px 0px" :data="spuSaleAttr">
        <el-table-column label="序号" type="index" width="85" />
        <el-table-column prop="saleAttrName" label="属性名" width="85" />
        <el-table-column prop="name" label="尺码">
          <template #="{ row, $index }">
            <el-tag
              style="margin: 0px 5px"
              v-for="item in row.spuSaleAttrValueList"
              :key="row.id"
              closable
              @close="row.spuSaleAttrValueList.splice($index,1)"
            >
              {{ item.saleAttrValueName }}
            </el-tag>
            <el-input @blur="toLook(row)" v-model="row.saleAttrValue" v-if="row.flag == true" placeholder="请输入属性值" size="small" style="width:100px"></el-input>
            <el-button @click="toEdit(row)" v-else type="success" size="small" icon="Plus"></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="85">
          <template #="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="spuSaleAttr.splice($index)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="default" @click="saveSpu">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
//引入组合式API函数ref
import { ref, computed } from "vue"
import { ElMessage, UploadProps } from "element-plus"
import {
  SpuAttrs,
  ResponseSpuAttrData,
  SpuProducts,
  AllTrademark,
  ProductAttrValueData,
  SpuData,
} from "../../../api/product/spu/type"
import {
  HasProductData,
  ImgsData,
  HasImgsData,
  ProductData,
} from "../../../api/product/sku/type"
import { getSpuAttr, getAllProduct } from "../../../api/product/spu/index"
import { getSpuImgs, getSpuAttrs } from "../../../api/product/sku/index"

let spuAttrArr = ref<SpuAttrs>([])

let productArr = ref<SpuProducts>([])

let spuImages = ref<ImgsData[]>([])

let spuSaleAttr = ref<ProductData[]>([])

let productName = ref<string>("")

let saleAttrValueObject = ref<string>("")

let spuObject = ref<SpuData>({
  spuName: "",
  description: "",
  category3Id: "",
  tmId: "",
  spuSaleAttrList: [],
  spuImageList: [],
})

let imgUrl = ref<string>()

let dialogVisible = ref<boolean>(false)

let $emit = defineEmits(["changeScene"])

const cancel = () => {
  $emit("changeScene", 0)
}

//上传图片组件->上传图片之前触发的钩子函数
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  //钩子是在图片上传成功之前触发,上传文件之前可以约束文件类型与大小
  //要求:上传文件格式png|jpg|gif 4M
  if (
    rawFile.type == "image/png" ||
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: "error",
        message: "上传文件大小小于4M",
      })
      return false
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传文件格式务必PNG|JPG|GIF",
    })
    return false
  }
}

const handlePictureCardPreview = (file: any) => {
  imgUrl.value = file.url
  dialogVisible.value = true
}

const handleRemove = () => {
  console.log(123)
}

const spuAttrList = async () => {
  if (spuAttrArr.value.length > 0) return
  let result: ResponseSpuAttrData = await getSpuAttr()
  if (result.code == 200) {
    spuAttrArr.value = result.data
  }
}

const spuHasImages = async (spuId: number) => {
  let result: HasImgsData = await getSpuImgs(spuId)
  if (result.code == 200) {
    spuImages.value = result.data.map((item) => {
      return {
        name: item.imgName,
        url: item.imgUrl,
      }
    })
  }
}

const spuProductAttr = async (spuId: number) => {
  let result: HasProductData = await getSpuAttrs(spuId)
  if (result.code == 200) {
    spuSaleAttr.value = result.data
  }
}

const spuProduct = async () => {
  if (productName.value.length > 0) return
  let result: AllTrademark = await getAllProduct()
  if (result.code == 200) {
    productArr.value = result.data
  }
}

const pushAttr = () => {
  const [baseSaleAttrId, saleAttrName] = saleAttrValueObject.value.split(":")

  let saleAttrParams: ProductData = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }

  spuSaleAttr.value.push(saleAttrParams)
  //清空收集的数据
  saleAttrValueObject.value = ""
}

const toEdit = (row: ProductData) => {
  row.flag = true
  row.saleAttrValue = ""
}

const toLook = (row: ProductData) => {
  row.flag = false
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrValue: ProductAttrValueData = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  //非法情况的判断
  if (saleAttrValue?.trim() == "") {
    ElMessage({
      type: "error",
      message: "属性值不能为空",
    })
  }
  //判断属性值是否存在
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage({
      type: "error",
      message: "属性重复",
    })
    return
  }
  //追加新的属性值
  row.spuSaleAttrValueList.push(newSaleAttrValue)
}

const saveSpu = () => {
  //照片墙数据
  // spuObject.value.spuImageList = spuImages.value.map((item) => {
  //   return {
  //     imgName: item.name,
  //     imgUrl: item.url,
  //   }
  // })
  // 整理销售属性数据
  spuObject.value.spuSaleAttrList = spuSaleAttr.value
}

let unSelectSaleAttr = computed(() => {
  let unSelectArr = spuAttrArr.value.filter((item) => {
    return spuSaleAttr.value.every((attr) => {
      return item.name != attr.saleAttrName
    })
  })
  return unSelectArr
})

const initHasSpuData = (SpuFormData: SpuData) => {
  spuObject.value = SpuFormData
  spuProduct()
  spuAttrList()
  spuHasImages(SpuFormData.id as number)
  spuProductAttr(SpuFormData.id as number)
}

defineExpose({ initHasSpuData })
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

/* .demo-form-inline .el-input {
  --el-input-width: 220px;
} */

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
